<template>
  <!-- 图片裁切容器 -->
  <div class="update-avatar">
    <img :src="img" ref="img" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="onChange">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import request from '@/utils/request'
export default {
  props: {
    img: {
      type: [Object, String],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  mounted() {
    // 初始化
    // 获取图片元素
    const image = this.$refs.img
    // 配置cropper
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 0, // 自动调整裁剪图片
      cropBoxMovable: true, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false, // 关闭默认背景
    })
  },
  methods: {
    onChange() {
      // 获取 裁剪后的 图片数据
      this.cropper.getCroppedCanvas().toBlob(async (imgBlob) => {
        try {
          const fd = new FormData()
          fd.append('file', imgBlob)
          const res = await request.post('http://124.223.14.236:8060/common/upload?type=images', fd, {
            headers: {
              'Content-Type': 'multipart/form-data',
            }
          })
          console.log(res.data.savePath)
          this.$emit('close',res.data.savePath)  //关闭弹层
          // this.$emit('onChangePhoto', res.data.data.photo) //更新视图
          this.$toast.success('上传成功')
        } catch (err) {
          this.$toast.fail('上传失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
// 头像裁切容器
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
img {
  max-width: 100%;
}
</style>